// UBBC 监控面板 JavaScript 功能

// Tab 切换功能
function showTab(tabName) {
    // 隐藏所有tab内容
    const tabs = document.querySelectorAll('.tab-content');
    tabs.forEach(tab => tab.classList.remove('active'));

    // 移除所有导航项的active状态
    const navItems = document.querySelectorAll('.nav-item');
    navItems.forEach(item => item.classList.remove('active'));

    // 显示选中的tab
    const selectedTab = document.getElementById(tabName);
    if (selectedTab) {
        selectedTab.classList.add('active');
    }

    // 高亮选中的导航项
    const selectedNav = event.target.closest('.nav-item');
    if (selectedNav) {
        selectedNav.classList.add('active');
    }
}

// 加载规则数据
async function loadRules() {
    try {
        const response = await fetch('/api/rules');
        const data = await response.json();

        const rulesList = document.getElementById('rules-list');
        if (data.rules && data.rules.length > 0) {
            rulesList.innerHTML = data.rules.map(rule =>
                `<div class="rule-item">
                    <h4>${rule.rule_name}</h4>
                    <p>${rule.description}</p>
                    <p><strong>关键词：</strong>${rule.keywords.join(', ')}</p>
                </div>`
            ).join('');
        } else {
            rulesList.innerHTML = '<p>暂无规则数据</p>';
        }

        showModal('规则加载完成！');
    } catch (error) {
        console.error('加载规则失败:', error);
        showModal('加载规则失败，请检查网络连接');
    }
}

// 添加新规则
function addRule() {
    const ruleName = prompt('请输入规则名称:');
    if (!ruleName) return;

    const description = prompt('请输入规则描述:');
    if (!description) return;

    const keywords = prompt('请输入关键词（用逗号分隔）:');
    if (!keywords) return;

    const ruleData = {
        rule_name: ruleName,
        description: description,
        keywords: keywords.split(',').map(k => k.trim())
    };

    // 这里可以添加保存规则的逻辑
    console.log('新规则数据:', ruleData);
    showModal('规则添加功能开发中...');
}

// 刷新日志
async function refreshLogs() {
    try {
        const response = await fetch('/api/logs');
        const data = await response.json();

        const logsContainer = document.getElementById('logs-container');
        if (data.logs && data.logs.length > 0) {
            logsContainer.innerHTML = data.logs.map(log =>
                `<div class="log-entry">${log}</div>`
            ).join('');
        } else {
            logsContainer.innerHTML = '<p>暂无日志数据</p>';
        }
    } catch (error) {
        console.error('加载日志失败:', error);
        showModal('加载日志失败，请检查网络连接');
    }
}

// 搜索日志
function filterLogs() {
    const searchTerm = document.getElementById('log-search').value.toLowerCase();
    const logEntries = document.querySelectorAll('.log-entry');

    logEntries.forEach(entry => {
        const text = entry.textContent.toLowerCase();
        if (text.includes(searchTerm)) {
            entry.style.display = 'block';
        } else {
            entry.style.display = 'none';
        }
    });
}

// 显示模态框
function showModal(message, title = '提示') {
    const modal = document.getElementById('modal');
    const modalTitle = document.getElementById('modal-title');
    const modalMessage = document.getElementById('modal-message');

    modalTitle.textContent = title;
    modalMessage.textContent = message;
    modal.style.display = 'block';
}

// 关闭模态框
function closeModal() {
    const modal = document.getElementById('modal');
    modal.style.display = 'none';
}

// 页面加载完成后的初始化
document.addEventListener('DOMContentLoaded', function() {
    // 初始化时显示仪表盘
    showTab('dashboard');

    // 加载初始数据
    loadRules();
    refreshLogs();

    // 定期刷新数据（每30秒）
    setInterval(() => {
        refreshLogs();
    }, 30000);
});

// 点击模态框外部关闭
window.onclick = function(event) {
    const modal = document.getElementById('modal');
    if (event.target === modal) {
        modal.style.display = 'none';
    }
}
